<?php
/**
 * Created by Sublime.
 * Author lingyun
 * Time:  2017-11-21 11:18:04
 * desc:  生产预估管理功能
 */
namespace app\store\controller;

use controller\BasicAdmin;
use service\DataService;
use think\Db;


class Estimate extends BasicAdmin
{
    /**
     * [index description]
     * Author   lingyun
     * DateTime 2017-11-20T17:46:01+0800
     * return   [type]                   [description]
     */

    public $table = "StoreOrderGoods";

    public function index()
    {
        $this->title = '订货预估';
        $store_id = session('user')['store_id'];
        $get = $this->request->get();

        $join = [
            ['ys_goods b', 'a.goods_id=b.id', 'LEFT'],
            ['ys_store_order c', 'a.order_id=c.id', 'LEFT'],
            ['ys_goods_spec_detail d', 'a.goods_spec_id=d.id', 'LEFT']
        ];
        $db = Db::name($this->table)->alias('a')->join($join)->field('a.*,b.name,b.unit,c.deal_time,c.sn,c.status,sum(a.rec_num) as sum,d.*,d.id as did')->where('a.store_id', $store_id)->where('c.status', 3);

        foreach (['name'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike('b.name', "%{$get[$key]}%");
        }

        if (isset($get['date']) && $get['date'] !== '') {
            list($start, $end) = explode('-', str_replace(' ', '', $get['date']));
            $this->assign('date', $start . " - " . $end);

            $start = $start . "  00:00:00";
            $end = $end . " 23:59:59";
            $start = strtotime($start);
            $end = strtotime($end);

            $db->whereBetween('a.rec_time', ["{$start}", "{$end}"]);

        } else {
            $this->assign('date', '');
        }

        $db->group('a.goods_spec_id');            //分组统计
        return parent::_list($db);
    }

    public function detail()
    {
        $store_id = session('user')['store_id'];
        $get = $this->request->get();

        $join = [
            ['ys_goods g', 'a.goods_id=g.id', 'LEFT'],
            ['ys_goods_spec_detail d', 'a.goods_spec_id=d.id', 'LEFT'],
            ['ys_store_order c', 'a.order_id=c.id', 'LEFT'],
        ];
        $db = Db::name($this->table)->alias('a')->join($join)->where(['a.store_id' => $store_id, 'a.goods_spec_id' => $get['id']])->field('a.*,g.*,d.*,a.addtime as atime,c.status')->where('c.status', 3);

        if (isset($get['date']) && $get['date'] !== '') {
            if (!isset($get['sign'])) {
                list($start, $end) = explode('+-+', str_replace(' ', '', $get['date']));
            } else {
                list($start, $end) = explode('-', str_replace(' ', '', $get['date']));
            }

            $this->assign('date', $start . " - " . $end);        //时间
            $start = $start . "  00:00:00";
            $end = $end . " 23:59:59";
            $start = strtotime($start);
            $end = strtotime($end);
            $db->whereBetween('a.addtime', ["{$start}", "{$end}"]);
        }
        $this->assign('id', $get['id']);
        $this->assign('title', '生产详情');
        return parent::_list($db);
    }

    /**
     * 营业额
     * @return array|string
     */
    public function chart()
    {
        $this->title = '线上订单营业额';
        $get = $this->request->get();
        $store_id = session('user')['store_id'];
        $db = Db::name('order')->where(['store_id'=>$store_id,'pay_status'=>1,'order_type'=>1])->order('id desc');
        $map['store_id'] = ['eq',$store_id];
        $map['order_type'] = ['eq',1];
        foreach (['order_sn'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike('order_sn', "%{$get[$key]}%");
            if(!empty($get['order_sn'])){
                $map['order_sn'] = ['like','%'.$get["order_sn"].'%'];
            }
        }

        if (isset($get['date']) && $get['date'] !== '') {
            list($start, $end) = explode('-', str_replace(' ', '', $get['date']));
            $this->assign('date', $start . " - " . $end);

            $start = $start . "  00:00:00";
            $end = $end . " 23:59:59";
            $start = strtotime($start);
            $end = strtotime($end);

            $db->whereBetween('addtime', ["{$start}", "{$end}"]);
            $map['addtime'] = array(
                array('gt',$start),
                array('lt',$end),
                'AND'
            );
        } else {
            $this->assign('date', '');
        }

        $count = db('order')->where($map)->sum('final_amount');
        $this->assign('all_amount',$count);

        return parent::_list($db);
    }

    /**
     * 营业额图表
     */
    public function volume()
    {
        $get = input('get.');
        $type = $get['type'];
        $date = $get['date'];
        if(empty($data)){
            $beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));
            $endThismonth=mktime(23,59,59,date('m'),date('t'),date('Y'));
            $date = date('Y/m/d',$beginThismonth).' - '.date('Y/m/d',$endThismonth);
        }

        $store_id = session('user')['store_id'];
        $store = db('store')->find($store_id);

        if ($date) {
            $date = explode(' - ', $date);
            $start = $date[0] . " 00:00:00";
            $end = $date[1] . " 23:59:59";
            $s = strtotime($start);
            $e = strtotime($end);
            $plus = 'and order_type=1 and  addtime>' . $s . ' and addtime<' . $e;
        } else
            $plus = 'and order_type=1';

        //按小时
//        $sql1 = "select FROM_UNIXTIME(addtime,'%Y-%m-%d %H') AS hours, sum(final_amount) as totalmoney, count(*) as num from ys_order WHERE store_id=" . $store_id . " group by hours ORDER BY hours";
        if ($type == 'day') {
            $sql = "select FROM_UNIXTIME(addtime,'%Y-%m-%d') AS hours, sum(final_amount-tuihuo_amount) as totalmoney, count(*) as num from ys_order WHERE store_id=" . $store_id . ' ' . $plus . " group by hours ORDER BY hours";
            $title = '营业额/按天';
        }

        if ($type == 'month') {
            $sql = "select FROM_UNIXTIME(addtime,'%Y-%m') AS hours, sum(final_amount-tuihuo_amount) as totalmoney, count(*) as num from ys_order WHERE store_id=" . $store_id . ' ' . $plus . " group by hours ORDER BY hours";
            $title = '营业额/按月';
        }

        $db = Db::query($sql);

        if (!is_array($date))
            foreach ($db as $key => $value) {
                if ($key == 0)
                    $start = $value['hours'];
                if ($key == count($db) - 1)
                    $end = $value['hours'];
            }

        foreach ($db as $key => $value) {
            $ndb[$value['hours']]['totalmoney'] = $value['totalmoney'];
            $ndb[$value['hours']]['num'] = $value['num'];
        }

        $dates = prDates($start, $end, $type);

        foreach ($dates as $value) {
            if (!isset($ndb[$value])) {
                $ndb[$value]['totalmoney'] = '0.00';
                $ndb[$value]['num'] = 0;
            }
        }
        ksort($ndb);

        foreach ($ndb as $key => $value) {
            $days[] = $key;
            $totalmoney[] = $value['totalmoney'];
        }

        $this->assign('days', json_encode($days));
        $this->assign('totalmoney', json_encode($totalmoney));
        $this->assign('title', $store['title'] . $title);
        return view();
    }

    /**
     * 订货预估
     */
    public function order()
    {
        $get = input('get.');
        $id = $get['id'];
        $date = $get['date'];
        $type = $get['type'];
        $title = $get['title'];
        $store_id = session('user')['store_id'];

        if ($date) {
            $date = explode(' - ', $date);
            $start = $date[0] . " 00:00:00";
            $end = $date[1] . " 23:59:59";
            $s = strtotime($start);
            $e = strtotime($end);
            $plus = ' and addtime>' . $s . ' and addtime<' . $e;
        } else
            $plus = '';

        $sqls = "select FROM_UNIXTIME(addtime,'%Y-%m-%d') AS hours, SUM(amount) AS nums, count(*) as num from ys_view_store_sale_goods WHERE storeid=" . $store_id . " and spec_id=" . $id . $plus . " group by hours ORDER BY hours";

        $sql = "select FROM_UNIXTIME(addtime,'%Y-%m-%d') AS hours, SUM(rec_num) AS nums, count(*) as num from ys_view_store_rec_goods WHERE store_id=" . $store_id . " and goods_spec_id=" . $id . $plus . " group by hours ORDER BY hours";

        $db = Db::query($sql);
        $dbs = Db::query($sqls);

        if (!is_array($date)){
            foreach ($db as $key => $value) {
                if ($key == 0)
                    $start = $value['hours'];
                if ($key == count($db) - 1)
                    $end = $value['hours'];
            }
            foreach ($dbs as $key => $value) {
                if ($key == 0 && $value['hours']<$start)
                    $start = $value['hours'];
                if ($key == count($dbs) - 1 && $value['hours']>$end)
                    $end = $value['hours'];
            }
        }

        foreach ($db as $key => $value) {
            $ndb[$value['hours']]['nums'] = $value['nums'];
            $ndb[$value['hours']]['num'] = $value['num'];
        }
        foreach ($dbs as $key => $value) {
            $sdb[$value['hours']]['nums'] = $value['nums'];
            $sdb[$value['hours']]['num'] = $value['num'];
        }

        $dates = prDates($start, $end, $type);

        foreach ($dates as $value) {
            if (!isset($ndb[$value])) {
                $ndb[$value]['nums'] = 0;
                $ndb[$value]['num'] = 0;
            }
            if (!isset($sdb[$value])) {
                $sdb[$value]['nums'] = 0;
                $sdb[$value]['num'] = 0;
            }
        }

        foreach ($ndb as $key => $value) {
            $nsdb[$key] = $sdb[$key];
        }
        ksort($ndb);
        ksort($nsdb);

        foreach ($ndb as $key => $value) {
            $days[] = $key;
            $nums1[] = $value['nums'];
            $nums2[] = $nsdb[$key]['nums'];
        }

        $this->assign('days', json_encode($days));
        $this->assign('num1', json_encode($nums1));
        $this->assign('num2', json_encode($nums2));
        $this->assign('title', $title);

        return view();
    }

    /**
     * @Author  lingyun
     * @Desc    线下订单营业额统计
     * 2018-05-07
     */
    public function under_order(){
        $this->title = '线下订单营业额';
        $get = $this->request->get();
        $store_id = session('user')['store_id'];
        $db = Db::name('order')->where(['store_id'=>$store_id,'pay_status'=>1,'order_type'=>0])->order('id desc');
        $map['store_id'] = ['eq',$store_id];
        $map['order_type'] = ['eq',0];
        $map['pay_status'] = ['eq',1];
        foreach (['order_sn'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike('order_sn', "%{$get[$key]}%");
            if(!empty($get['order_sn'])){
                $map['order_sn'] = ['like','%'.$get["order_sn"].'%'];
            }
        }

        if (isset($get['date']) && $get['date'] !== '') {
            list($start, $end) = explode('-', str_replace(' ', '', $get['date']));
            $this->assign('date', $start . " - " . $end);

            $start = $start . "  00:00:00";
            $end = $end . " 23:59:59";
            $start = strtotime($start);
            $end = strtotime($end);

            $db->whereBetween('addtime', ["{$start}", "{$end}"]);
            $map['addtime'] = array(
                array('gt',$start),
                array('lt',$end),
                'AND'
            );
        } else {
            $this->assign('date', '');
        }

        $count = db('order')->where($map)->sum('final_amount');

        $this->assign('all_amount',$count);

        return parent::_list($db);
    }

    /**
     * @Author  lingyun
     * @Desc    线下订单
     * 2018-05-07
     */
    public function under_volume(){
        $get = input('get.');
        $type = $get['type'];
        $date = $get['date'];
        $store_id = session('user')['store_id'];
        $store = db('store')->find($store_id);
        if(empty($data)){
            $beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));
            $endThismonth=mktime(23,59,59,date('m'),date('t'),date('Y'));
            $date = date('Y/m/d',$beginThismonth).' - '.date('Y/m/d',$endThismonth);
        }
        if ($date) {
            $date = explode(' - ', $date);
            $start = $date[0] . " 00:00:00";
            $end = $date[1] . " 23:59:59";
            $s = strtotime($start);
            $e = strtotime($end);
            $plus = 'and order_type=0 and addtime>' . $s . ' and addtime<' . $e;
        } else
            $plus = 'and order_type=0';

        //按小时
//        $sql1 = "select FROM_UNIXTIME(addtime,'%Y-%m-%d %H') AS hours, sum(final_amount) as totalmoney, count(*) as num from ys_order WHERE store_id=" . $store_id . " group by hours ORDER BY hours";
        if ($type == 'day') {
            $sql = "select FROM_UNIXTIME(addtime,'%Y-%m-%d') AS hours, sum(final_amount-tuihuo_amount) as totalmoney, count(*) as num from ys_order WHERE store_id=" . $store_id . ' ' . $plus . " group by hours ORDER BY hours";
            $title = '营业额/按天';
        }

        if ($type == 'month') {
            $sql = "select FROM_UNIXTIME(addtime,'%Y-%m') AS hours, sum(final_amount-tuihuo_amount) as totalmoney, count(*) as num from ys_order WHERE store_id=" . $store_id . ' ' . $plus . " group by hours ORDER BY hours";
            $title = '营业额/按月';
        }

        $db = Db::query($sql);

        if (!is_array($date))
            foreach ($db as $key => $value) {
                if ($key == 0)
                    $start = $value['hours'];
                if ($key == count($db) - 1)
                    $end = $value['hours'];
            }

        foreach ($db as $key => $value) {
            $ndb[$value['hours']]['totalmoney'] = $value['totalmoney'];
            $ndb[$value['hours']]['num'] = $value['num'];
        }

        $dates = prDates($start, $end, $type);

        foreach ($dates as $value) {
            if (!isset($ndb[$value])) {
                $ndb[$value]['totalmoney'] = '0.00';
                $ndb[$value]['num'] = 0;
            }
        }
        ksort($ndb);

        foreach ($ndb as $key => $value) {
            $days[] = $key;
            $totalmoney[] = $value['totalmoney'];
        }

        $this->assign('days', json_encode($days));
        $this->assign('totalmoney', json_encode($totalmoney));
        $this->assign('title', $store['title'] . $title);
        return view();
    }


}
